<?php


namespace system\compute\trie;


class Trie
{
    protected $nextMap = [];
    protected $currentNumber = 0;
    protected $currentChar = '';
    public function __construct($currentChar = '')
    {
        $this->currentChar = $currentChar;
    }
    public function findOrCreateNext(string $str): Trie
    {
        if (strlen($str) == 0) {
            $this->currentNumber++;
        }else{
            $char = substr($str, 0, 1);
            if (!array_key_exists($char, $this->nextMap)) {
                $this->nextMap[$char] = new Trie($char);
            }
            /**
             * @var Trie $trie
             */
            $trie = $this->nextMap[$char];
            $trie->findOrCreateNext(substr($str, 1));
        }
        return $this;
    }
    public function getDisplayNumber($parentChar = ''): array
    {
        $result = [];
        if ($this->currentNumber != 0 ) {
            $result[$parentChar . $this->currentChar] = $this->currentNumber;
        }
        foreach ($this->nextMap as $value) {
            /**
             * @var Trie $value
             */
            $childrenNumber = $value->getDisplayNumber($parentChar . $this->currentChar);
            $result = array_merge($result, $childrenNumber);
        }

        return $result;
    }
}